package com.jinxiangyang.aop;

import com.jinxiangyang.domain.UserLoginLog;
import com.jinxiangyang.domain.vo.LoginBody;
import com.jinxiangyang.service.UserLoginLogService;
import com.jinxiangyang.utils.AddressUtils;
import com.jinxiangyang.utils.IpUtils;
import com.jinxiangyang.utils.ServletUtils;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;

/**
 * @author jinxiangyang
 * @date 2023/8/23 9:33
 * @description TODO
 **/

@Aspect
@Component
@Slf4j
public class LoginLogAop {



    @Autowired
    private UserLoginLogService userLoginLogService;





    @Pointcut("@annotation(com.jinxiangyang.annotation.LoginLog)")
    public void pointCut(){
    }



    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint)throws Throwable{

        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        String signature = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        LoginBody arg = (LoginBody) args[0];
        String ipAddr = IpUtils.getIpAddr();
        String address = AddressUtils.getRealAddressByIP(ip);
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setCity(address);
        userLoginLog.setType(arg.getType());
        Browser browser = userAgent.getBrowser();
        userLoginLog.setBrowser(browser.getName());
        userLoginLog.setIp(ipAddr);
        userLoginLog.setUserName(String.valueOf(arg.getUsername()));
        log.info("执行方法:{},< ===== {}",signature, Arrays.toString(args));
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            userLoginLog.setMsg(proceed.toString());
        } catch (Throwable e) {
            userLoginLog.setMsg("失败");
        }
        log.info("执行方法:{},< ===== {}",signature,proceed);
        userLoginLogService.save(userLoginLog);
        return  proceed;
    }









}
